#include "TopDefine.h"
#include "shoot.hpp"
#include "main.h"
#include "remote_control.h"
#include "FreeRTOS.h"
#include <cmsis_os2.h>
#include "calc_lib.h"

extern RC_ctrl_t rc_ctrl;
#define SHOOT_SPEED 40000
#define SHOOT_SPEED_BACK -2000
#define STOP 0
#define Trigger 3000

const fp32 Shoot:: M2006_speed_PID[3] = {5, 0.01, 0};
int t=0;

Shoot::Shoot()
{
    //扳机初始化
    trigger_Motor= get_motor_point(4);
    trigger_Motor->type=M3508;
    PID_init(&speed_pid,PID_POSITION,M2006_speed_PID,16000, 10000);//pid初始化
    speedSet = 0; 
    result = 0;
   
    //发射摩擦轮
    motor_5065[0] = get_vesc_point(0);//获取电机数据指针
    motor_5065[1] = get_vesc_point(1);//获取电机数据指针
    speed_5065=0;
    currentState= SHOOT_IDLE;
}

void Shoot::trigger_spin()
{
    if(t>0)
    {
        speedSet=Trigger;
        if(trigger_Motor->speed_rpm<5)
        {
            speedSet=-Trigger;
        }
    }

}

void Shoot::shootThree()
{
    if((rc_ctrl.sw[1]>500))
    {
        speed_5065 = SHOOT_SPEED;
        
    }
    else
    {
        speed_5065=STOP;

    }
    if(rc_ctrl.sw[5]==1694)
    {
        speed_5065=SHOOT_SPEED_BACK;

    }
    CAN_VESC_Control(1,speed_5065,&hcan2);
    // CAN_VESC_RPM(1, speed_5065); 
    // CAN_VESC_RPM(2, speed_5065); 
}

void Shoot::shootBack()
{
    if(rc_ctrl.sw[5]==1694)
    {
        
        CAN_VESC_RPM(1, SHOOT_SPEED_BACK); 
        CAN_VESC_RPM(2, SHOOT_SPEED_BACK);
    }

}

void Shoot::shootStop()
{
    CAN_VESC_HEAD(1); 
    CAN_VESC_HEAD(2); 
  
}

void Shoot::shootStateMachine() {
    switch (currentState) {
        case SHOOT_IDLE: {
            // 空闲状态，等待遥控器输入
            if (rc_ctrl.sw[1] > 500) {
                currentState = SHOOT_FIRE; // 切换到发射状态
            }
            break;
        }

        case SHOOT_FIRE: {
            // 发射状态，控制电机发射
            speed_5065 = map((float)rc_ctrl.sw[1], 500, 1694, 30000, 45000);
            CAN_VESC_RPM(1, speed_5065); 
            CAN_VESC_RPM(2, speed_5065); 

            // 检测光电传感器是否触发
            if (IS_PHOTOELECTRIC_TRIGGERED()) {
                currentState = SHOOT_TRIGGERED; // 切换到光电触发状态
            }
            break;
        }

        case SHOOT_TRIGGERED: {
            // 光电触发状态，停止发射
            CAN_VESC_HEAD(1); 
            CAN_VESC_HEAD(2);
            // 切换到返回状态
            currentState = SHOOT_RETURN;
            break;
        }

        case SHOOT_RETURN: {
            // 自动返回状态，控制电机反转
            CAN_VESC_RPM(1, SHOOT_SPEED_BACK); 
            CAN_VESC_RPM(2, SHOOT_SPEED_BACK);

            // 检测返回完成（可以通过时间或其他传感器判断）
            if (rc_ctrl.sw[1] < 500) { // 假设遥控器开关控制返回完成
                currentState = SHOOT_IDLE; // 切换回空闲状态
            }
            break;
        }

        default: {
            // 默认状态，回到空闲
            currentState = SHOOT_IDLE;
            break;
        }
    }
}
